package com.example.chess.api;

import com.example.chess.game.OnlineUserManager;
import com.example.chess.game.RoomManager;
import com.example.chess.mapper.UserMapper;
import com.example.chess.model.User;
import com.example.chess.util.OnlineUserResponse;
import com.example.chess.util.ResState;
import com.example.chess.util.ResponseBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
@RequestMapping("/user")
public class UserAPI {

    @Resource
    private UserMapper userMapper;

    @Resource
    private OnlineUserManager onlineUserManager;// 在线的用户

    @Resource
    private RoomManager roomManager;

    @RequestMapping(value = "/login")
    public ResponseBody<User> login(@RequestParam String username, @RequestParam String password, HttpServletRequest request){
        User user = userMapper.getUserByName(username);
        if (user == null || !user.getPassword().equals(password)){
            return new ResponseBody<>(ResState.FAIL, "登录失败", null);
        }
        user.setPassword("");
        HttpSession session = request.getSession(true);
        session.setAttribute("user", user);
        return new ResponseBody<>(ResState.SUCCESS, "登录成功", user);
    }


    @RequestMapping("/register")
    public ResponseBody<User> register(@RequestParam String username, @RequestParam String nickname,
                                       @RequestParam String password, @RequestParam String email) {
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        user.setPassword(password);
        user.setEmail(email);
        User checkUser = userMapper.getUserByName(username);
        if (checkUser != null){
            return  new ResponseBody<>(ResState.EXIST, "该用户名已存在", null);
        }
        int ret = userMapper.insert(user);
        if (ret == 1){
            return new ResponseBody<>(ResState.SUCCESS, "注册成功", user);
        }else {
            return new ResponseBody<>(ResState.FAIL, "注册失败", null);
        }
    }

    @RequestMapping("/getuserinfo")
    public ResponseBody<User> getUserInfo(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) return new ResponseBody<>(ResState.FAIL, "未登录", null);
        User user = (User)session.getAttribute("user");
        User newUser = userMapper.getUserByName(user.getUsername());
        if (newUser == null){
            return new ResponseBody<>(ResState.FAIL, "未登录", null);
        }else {
            return new ResponseBody<>(ResState.SUCCESS, "返回成功", newUser);
        }
    }

    /**
     * 获取在线用户信息
     * @return
     */
    @RequestMapping("/getonlineUsers")
    public ResponseBody<List<User>> getOnlineUsers(HttpServletRequest request){
        List<User> onlineUsers = new ArrayList<>();
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null){
            System.out.println("用户未登录,无法获取在线用户列表信息");
            return new ResponseBody<>(ResState.FAIL, "用户未登录, 无法获取在线用户信息", null);
        }
        User user = (User)session.getAttribute("user");
        // 得到在线的人的信息
        Set<Map.Entry<Integer, WebSocketSession>> onlineEntries = onlineUserManager.getGameHall().entrySet();
        for (Map.Entry<Integer, WebSocketSession> entry : onlineEntries) {
            if (entry.getKey() == user.getUserId()) continue;// 是当前用户, 不显示
            // 得到每一个在线用户
            User retUser = userMapper.getUserById(entry.getKey());
            retUser.setState("online");
            retUser.setPassword("");
            retUser.setEmail("");
            // 添加
            onlineUsers.add(retUser);
        }

        // 得到在游戏中的用户的 id
        Set<Map.Entry<Integer, String>> gameEntries = roomManager.getUserRoom().entrySet();
        for (Map.Entry<Integer, String> entry : gameEntries) {
            if (entry.getKey() == user.getUserId()) continue;// 是当前用户, 不显示
            // 得到每一个在线用户
            User retUser = userMapper.getUserById(entry.getKey());
            retUser.setRoomId(entry.getValue());// 用户的游戏房间号
            retUser.setState("game");// 游戏中
            retUser.setPassword("");
            retUser.setEmail("");
            onlineUsers.add(retUser);
        }
        return new ResponseBody<>(ResState.SUCCESS, "返回在线用户信息成功", onlineUsers);
    }
}
